package com.xuecheng.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.basic.domain.Category;
import com.xuecheng.basic.mappers.CategoryMapper;
import com.xuecheng.basic.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.model.vo.CategoryVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.BeanHelper;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-16
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public ResponseResult treeNodes() {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getParentid,0);
        Category fatherCategory = this.getOne(queryWrapper);
        CategoryVo fatherCategoryVo = BeanHelper.copyProperties(fatherCategory, CategoryVo.class);
        List<Category> categoryList = findByParentId(fatherCategoryVo.getId());
        List<CategoryVo> categoryVoList = BeanHelper.copyWithCollection(categoryList, CategoryVo.class);

        for (CategoryVo categoryVo : categoryVoList) {
            List<Category> categoryList2 = findByParentId(categoryVo.getId());
            List<CategoryVo> categoryVos = BeanHelper.copyWithCollection(categoryList2, CategoryVo.class);
            categoryVo.setCategoryTreeNodes(categoryVos);
        }

        fatherCategoryVo.setCategoryTreeNodes(categoryVoList);
        return ResponseResult.okResult(fatherCategoryVo);
    }

    private List<Category> findByParentId(String parentId) {
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(Category::getParentid,parentId);
        return this.list(qw);
    }

}
